from PyQt5.QtGui import QTextCharFormat, QColor, QTextCursor
from PyQt5.QtWidgets import QVBoxLayout, QPushButton, QLineEdit
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QHBoxLayout, QLabel, QTextEdit, \
    QButtonGroup, QRadioButton

import file_tools
import utils


class MainWindow(QWidget):

    def __init__(self):
        super().__init__()
        self.crontab_time = None
        self.xml_content = None
        self.radio_button1 = None
        self.radio_button2 = None
        self.button_group = None
        self.local_path = '/Users/liuhai/Documents/projectfiles/站点设备检查脚本/目标文件/SysSetting.xml'
        self.right_edit = None  # 修改后文本展示
        self.text_edit = None  # 修改前文本展示
        self.code_input = None
        self.init_ui()
        self.remote_file_path = None

    def init_ui(self):
        self.setWindowTitle('AFC Setting Check')
        self.resize(1200, 600)

        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)

        layout = QVBoxLayout()
        # 编号输入和检查
        layout.addLayout(self.init_header_layout())
        # 信息展示
        layout.addLayout(self.init_file_block())
        # # # 表格布局
        # layout.addLayout(init_table_layout())
        # # # 底部布局
        layout.addLayout(self.init_footer_layout())
        layout.addStretch()
        self.setLayout(layout)

    # 文本内容显示
    def init_file_block(self):
        text_layout = QHBoxLayout()
        # 左侧源文件
        label_title = QLabel()
        label_title.setText("源文件")
        self.text_edit = QTextEdit(self)
        self.text_edit.setPlaceholderText("展示读取到的配置文件内容")
        text_layout.addWidget(label_title)
        text_layout.addWidget(self.text_edit)
        # 右侧更改后文件
        select_layout = QVBoxLayout()
        label_title = QLabel()
        label_title.setText("修改后")

        self.button_group = QButtonGroup()
        self.button_group.buttonClicked.connect(lambda: self.on_radio_button_clicked)
        self.radio_button1 = QRadioButton('进站', self)
        self.radio_button2 = QRadioButton('出站', self)

        select_layout.addWidget(self.radio_button1)
        select_layout.addWidget(self.radio_button2)

        self.button_group.addButton(self.radio_button1)
        self.button_group.addButton(self.radio_button2)

        self.radio_button1.hide()
        self.radio_button2.hide()

        select_layout.addWidget(label_title)
        text_layout.addLayout(select_layout)
        self.right_edit = QTextEdit(self)
        self.right_edit.setPlaceholderText("展示修改后的配置文件内容")

        text_layout.addWidget(self.right_edit)
        return text_layout

    def init_header_layout(self):
        # 顶部布局
        header_layout = QHBoxLayout()
        # code输入
        self.code_input = QLineEdit(self)
        self.code_input.setPlaceholderText("请输入编号")
        self.code_input.setFixedWidth(200)
        header_layout.addWidget(self.code_input)
        # 开始按钮
        start_button = QPushButton("开始检查")
        start_button.clicked.connect(self.start_check)
        header_layout.addWidget(start_button)


        # test
        # remote_button = QPushButton("测试连接")
        # remote_button.clicked.connect(self.start_connect)
        # header_layout.addWidget(remote_button)

        # test

        header_layout.addStretch()
        return header_layout

    def init_footer_layout(self):
        foot_layout = QVBoxLayout()

        crontab_layout = QHBoxLayout()
        self.crontab_time = QLineEdit(self)
        self.crontab_time.setFixedWidth(100)
        self.crontab_time.setPlaceholderText("请输入时间")
        crontab_layout.addWidget(self.crontab_time)

        crontab_button = QPushButton('修改定时任务')
        crontab_button.clicked.connect(lambda: self.crontab_update())
        crontab_layout.addWidget(crontab_button)
        crontab_layout.addStretch()
        foot_layout.addLayout(crontab_layout)

        update_layout = QHBoxLayout()
        # 更新按钮
        update_button = QPushButton("一键更正")
        update_button.clicked.connect(self.start_update)
        update_layout.addWidget(update_button)

        reboot_button = QPushButton("重启设备")
        # reboot_button.setStyleSheet("QPushButton { background-color: red; }")
        reboot_button.clicked.connect(lambda: self.reboot_device())
        update_layout.addWidget(reboot_button)
        update_layout.addStretch()
        foot_layout.addLayout(update_layout)

        return foot_layout

    def crontab_update(self):
        file_utils = file_tools.FileUtils()
        ssh_client = file_utils.ssh_connect(self, self.code_input.text())
        file_utils.update_crontab(self.crontab_time.text(), ssh_client)

    def start_connect(self):
        file_utils = file_tools.FileUtils()
        file_utils.read_remote_xml(self.code_input.text(), self.remote_file_path)

    # 重启设备
    def reboot_device(self):
        print("重启设备")
        file_utils = file_tools.FileUtils()
        ssh_client = file_utils.ssh_connect(self, self.code_input.text())
        file_utils.remote_reboot(self.code_input.text(), ssh_client)

    def start_check(self):
        device_type = utils.divide_code(self.code_input.text())[2]  # 获取设备类型
        self.radio_button1.hide()
        self.radio_button2.hide()
        if device_type == "10":  # ITM
            self.remote_file_path = '/home/AFC/tvm/Config/SysSetting.xml'
            self.check_itm()

        if device_type == "02":  # TVM
            self.remote_file_path = '/home/AFC/tvm/Config/SysSetting.xml'
            self.check_itm()

        if device_type == "03":  # BOM
            self.remote_file_path = '/home/AFC/BOM/data/Config.ini'
            self.check_bom()

        if device_type == "04":  # AG 04 进站闸机 05 出站闸机 06 双向闸机
            self.remote_file_path = '/home/AFC/AG_28/cfg/config.xml'
            self.check_ag(device_type)

        if device_type == "05":
            self.remote_file_path = '/home/AFC/AG_28/cfg/config.xml'
            self.check_ag(device_type)

        if device_type == "06":
            self.remote_file_path = '/home/AFC/AG_28/cfg/config.xml'
            self.radio_button1.show()
            self.radio_button2.show()
            self.check_ag(device_type)

    # 检查ITM配置文件
    def check_itm(self):

        file_utils = file_tools.FileUtils()
        ssh_client = file_utils.ssh_connect(self, self.code_input.text())
        # xml_content = file_utils.read_local_xml(self, self.local_path)
        xml_content = file_utils.read_remote_xml(ssh_client, self.remote_file_path)
        self.text_edit.setPlainText(xml_content)

        input_code = self.code_input.text()
        target_value = utils.divide_code(input_code)[1]
        warning_list = []
        errors = file_utils.check_and_modify_settings(self, xml_content, self.code_input.text())
        if len(errors) == 0:  # 无错误内容
            print("没有错误")
        else:  # 存在错误
            for info in errors:
                if info['line'] == 0:  # 第一行内容处理
                    if 'gateWay' in info:
                        warning_list.append(info["gateWay"])
                        self.change_text_color(info["gateWay"])
                        new_gateway = utils.modify_ip(info["gateWay"], target_value)  # 修改IP
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'dev', 'gateWay',
                                                                         new_gateway)
                    if 'code' in info:
                        warning_list.append(info["code"])
                        self.change_text_color(info["code"])
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'dev', 'code', input_code)
                    if 'ip' in info:
                        warning_list.append(info["ip"])
                        self.change_text_color(info["ip"])
                        new_gateway = utils.modify_ip(info["ip"], target_value)
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'dev', 'ip', new_gateway)

                if info['line'] == 1:
                    if 'code' in info:
                        warning_list.append(info["code"])
                        self.change_text_color(info["code"])
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'ftp', 'code', input_code)
                    if 'ip' in info:
                        warning_list.append(info["ip"])
                        self.change_text_color(info["ip"])
                        new_gateway = utils.modify_ip(info["ip"], target_value)
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'ftp', 'ip', new_gateway)
                if info['line'] == 2:
                    if 'code' in info:
                        warning_list.append(info["code"])
                        self.change_text_color(info["code"])
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'sc', 'code', input_code)
                    if 'ip' in info:
                        warning_list.append(info["ip"])
                        self.change_text_color(info["ip"])
                        new_gateway = utils.modify_ip(info["ip"], target_value)
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'sc', 'ip', new_gateway)
                if info['line'] == 3:
                    if 'code' in info:
                        warning_list.append(info["code"])
                        self.change_text_color(info["code"])
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'acc', 'code', input_code)
                    if 'ip' in info:
                        warning_list.append(info["ip"])
                        self.change_text_color(info["ip"])
                        new_gateway = utils.modify_ip(info["ip"], target_value)
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'acc', 'ip', new_gateway)
                if info['line'] == 4:
                    if 'enabled' in info:
                        warning_list.append(info['enabled'])
                        # self.change_text_color(info['enabled'])
                        xml_content = file_utils.replace_attribute_value(self, xml_content, 'cashcoin', 'enabled', '0')
            self.right_edit.setText(xml_content)

    # 检查 AG配置文件
    def check_ag(self, device_type):
        file_utils = file_tools.FileUtils()
        self.xml_content = file_utils.read_local_xml(self, self.local_path)
        self.text_edit.setPlainText(self.xml_content)
        xml_dict = file_utils.parse_xml_to_dict(self, self.xml_content)
        station_code = utils.divide_code(self.code_input.text())[1]

        if station_code != xml_dict['sc_svr_ip'].split(".")[2]:
            self.highlight_ag_xml('sc_svr_ip')
            new_sc_svr_ip = utils.modify_ip(xml_dict['sc_svr_ip'], station_code)
            self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'sc_svr_ip', new_sc_svr_ip)
        if station_code != xml_dict['sc_ftp_ip'].split(".")[2]:
            self.highlight_ag_xml('sc_ftp_ip')
            new_sc_ftp_ip = utils.modify_ip(xml_dict['sc_ftp_ip'], station_code)
            self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'sc_ftp_ip', new_sc_ftp_ip)

        if self.code_input.text() != xml_dict['device_id']:
            self.highlight_ag_xml(xml_dict['device_id'])
            self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'device_id',
                                                             self.code_input.text())
        if device_type == '04':
            if xml_dict['ag_type'] != '01':
                self.highlight_ag_xml("ag_type")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_type', "01")
            if xml_dict['channel_type'] != '1':
                self.highlight_ag_xml("channel_type")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'channel_type', "1")
            if xml_dict['ag_channel_direction'] != '1':
                self.highlight_ag_xml("ag_channel_direction")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_channel_direction', "1")
        if device_type == '05':
            if xml_dict['ag_type'] != '02':
                self.highlight_ag_xml("ag_type")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_type', "02")
            if xml_dict['channel_type'] != '2':
                self.highlight_ag_xml("channel_type")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'channel_type', "2")
            if xml_dict['ag_channel_direction'] != '2':
                self.highlight_ag_xml("ag_channel_direction")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_channel_direction', "2")

        if device_type == '06':
            self.highlight_ag_xml("ag_channel_direction")  # 需要根据现场情况更改
            if xml_dict['ag_type'] != '03':
                self.highlight_ag_xml("ag_type")
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_type', "03")
            if xml_dict['channel_type'] != '3':
                self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'channel_type', "3")
                self.highlight_ag_xml("channel_type")
            if xml_dict['ag_channel_direction'] == "1":
                self.radio_button1.setChecked(True)
            if xml_dict['ag_channel_direction'] == "2":
                self.radio_button2.setChecked(True)

        self.right_edit.setText(self.xml_content)

    # 检查 BOM
    def check_bom(self):
        file_utils = file_tools.FileUtils()
        # 读取本地文件
        self.xml_content = file_utils.read_local_xml(self, self.local_path)
        # 解析文件成字典
        bom_content_dict = file_utils.parse_bom_file_to_dict(self, self.xml_content)
        self.text_edit.setPlainText(self.xml_content)
        station_code = utils.divide_code(self.code_input.text())[1]

        device_code = bom_content_dict['local']['deviceCode']
        if device_code != utils.divide_code(self.code_input.text())[3]:
            self.highlight_bom_key('deviceCode')
            self.xml_content = file_utils.update_bom_value("deviceCode",
                                                           utils.divide_code(self.code_input.text())[3],
                                                           content=self.xml_content)
        if (self.code_input.text()[:4]) != bom_content_dict['local']['stationCode']:
            self.highlight_bom_key('stationCode')
            self.xml_content = file_utils.update_bom_value("stationCode",
                                                           self.code_input.text()[:4],
                                                           content=self.xml_content)
        if station_code != bom_content_dict['commun']['ftpip'].split(".")[2]:
            self.highlight_bom_key('ftpip')
            ftpip = utils.modify_ip(bom_content_dict['commun']['ftpip'], station_code)
            self.xml_content = file_utils.update_bom_value("ftpip",
                                                           ftpip,
                                                           content=self.xml_content)

        if station_code != bom_content_dict['commun']['socketip'].split(".")[2]:
            self.highlight_bom_key('socketip')
            socketip = utils.modify_ip(bom_content_dict['commun']['socketip'], station_code)
            self.xml_content = file_utils.update_bom_value("socketip",
                                                           socketip,
                                                           content=self.xml_content)

        self.right_edit.setText(self.xml_content)
        print(bom_content_dict)

    # 开始更新
    def start_update(self):
        file_utils = file_tools.FileUtils()
        ssh_client = file_utils.ssh_connect(self, self.code_input.text())
        update_content = self.right_edit.toPlainText()
        new_permissions = 0o666
        # file_utils.update_file(self.local_path, update_content, new_permissions)
        file_utils.update_remote_file(update_content, ssh_client, self.remote_file_path)

    # 错误内容显示红色 ITM
    def change_text_color(self, target_text):
        text_format = QTextCharFormat()
        text_format.setForeground(QColor("blue"))  # 设置颜色为红色

        cursor = self.text_edit.textCursor()
        document = self.text_edit.document()
        pos = document.toPlainText().find(target_text)

        while pos != -1:
            cursor.setPosition(pos)
            cursor.setPosition(pos + len(target_text), QTextCursor.KeepAnchor)
            cursor.setCharFormat(text_format)
            pos = document.toPlainText().find(target_text, pos + 1)

    # AG
    def highlight_ag_xml(self, tag):
        content = self.text_edit.toPlainText()
        cursor = self.text_edit.textCursor()

        format_red = QTextCharFormat()
        format_red.setForeground(QColor("blue"))

        # Store the current text cursor position
        original_position = cursor.position()

        pos = content.find(f"<t>{tag}</t>")
        while pos != -1:
            v_start = content.find("<v>", pos)
            v_end = content.find("</v>", v_start)
            if v_start != -1 and v_end != -1:
                cursor.setPosition(v_start + len("<v>"))
                cursor.setPosition(v_end, QTextCursor.KeepAnchor)
                cursor.setCharFormat(format_red)
                pos = content.find(f"<t>{tag}</t>", v_end)
            else:
                break

        # Restore the original text cursor position
        cursor.setPosition(original_position)

        self.text_edit.setTextCursor(cursor)

    # BOM 错误高亮
    def highlight_bom_key(self, key):
        cursor = self.text_edit.textCursor()
        content = self.text_edit.toPlainText()
        format_red = QTextCharFormat()
        format_red.setForeground(QColor("blue"))

        # Store the current text cursor position
        original_position = cursor.position()

        lines = content.strip().split('\n')
        current_section = None

        for line in lines:
            line = line.strip()

            if line.startswith('[') and line.endswith(']'):
                current_section = line[1:-1]
            elif current_section and '=' in line:
                line_key, line_value = line.split('=', 1)
                if line_key.strip() == key:
                    cursor_position = content.find(line_value)
                    while cursor_position != -1:
                        value_end = cursor_position + len(line_value)
                        cursor.setPosition(cursor_position)
                        cursor.setPosition(value_end, QTextCursor.KeepAnchor)
                        cursor.setCharFormat(format_red)
                        cursor_position = content.find(line_value, value_end)

        # Restore the original text cursor position
        cursor.setPosition(original_position)

        self.text_edit.setTextCursor(cursor)

    def on_radio_button_clicked(self, button):
        file_utils = file_tools.FileUtils()
        index = self.button_group.id(button)
        if index == -2:
            self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_channel_direction', "1")
        if index == -3:
            self.xml_content = file_utils.modify_xml_content(self, self.xml_content, 'ag_channel_direction', "2")
        self.right_edit.setText(self.xml_content)
        print(f"Selected index: {index}")
